package com.app.shop.util;

import java.security.NoSuchAlgorithmException;
import java.util.Random;


/**
 * 生成随机密码,密码加密工具类
 *
 * @author chenliwei
 * @version v1.0 2017-11-5
 */
public class PwdUtil {

    /**
     * 生成8为随机密码
     *
     * @return 密码随机码
     * @author chenliwei
     */
    public static String getPwd() {

        final int maxNum = 36;
        int i; // 生成的随机数
        int count = 0; // 生成的密码的长度
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < 9) {
            // 生成随机数，取绝对值，防止生成负数，
            i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }


    /**
     * 校验密码 (个人设置密码)
     * 1、长度不小于8位
     * 2、必须以字母开头
     * 3、必须包含数字
     *
     * @param pwd
     * @return 返回是否符合规则
     * @author chenliwei
     */
    public static boolean validPwd(String pwd) {
        if (pwd == null || "".equals(pwd)) {
            return false;
        }
        if (pwd.length() < 8) {
            return false;
        }
        if (pwd.matches("(.*)[a-zA-z](.*)") && pwd.matches("(.*)\\d+(.*)")) {
            return true;
        }
        return false;
    }


    /**
     * 密码加密函数
     *
     * @param password 需要加密的密码
     * @return 返回加密后密码
     * @throws NoSuchAlgorithmException
     * @author chenliwei
     */
    public static String encryptPassword(String password)
            throws NoSuchAlgorithmException {
        String returnString = null;
        byte[] digestc = null;
        java.security.MessageDigest algc = java.security.MessageDigest
                .getInstance("MD5");
        algc.update(password.getBytes());
        digestc = algc.digest();
        returnString = byte2hex(digestc);
        return returnString;
    }


    /**
     * 二行制转字符串
     *
     * @param b
     * @return
     * @author chenliwei
     */
    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }


}
